package com.gai.shop.web.filter;

import com.gai.shop.common.Const;
import com.gai.shop.entity.User;
import com.gai.shop.service.UserService;
import com.gai.shop.service.impl.UserServiceImpl;
import com.gai.shop.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //1检查cookie
        Cookie[] cookies = request.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            //直接进行name值的比对
            if (cookie.getName().equals(Const.UserConst.AUTO_LOGIN)){
                //用户有设置自动登录，并且已有登录成功
                value = cookie.getValue();//获取的是加密过的用户名和密码的拼接字符串
            }
        }
        if (value != null){
            //解码==>用户名:密码
            String[] split = Base64Utils.decode(value).split(Const.COLON);
            String uname = split[0];
            String upassword = split[1];
            //再次进行用户名和密码的验证，防止用户在其他地方已经有修改过密码
            UserService us = new UserServiceImpl();
            User user = us.selectUserByUname(uname);
            if (user.getUpassword().equals(upassword)){
                //用户名和密码没有变更，所以就直接帮用户进行登录
                request.getSession().setAttribute(Const.LOGIN_USER,user);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }else {
            //用户没有在cookie中保存信息，即自动登录没有设置或者过期
            //直接放行到login.jsp
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
